{% extends 'admin/base.html' %}

{% block title %}自行车管理 - 管理后台{% endblock %}
{% block page_title %}自行车管理{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-list-ul"></i> 自行车管理</h2>
            <div>
                <a href="{% url 'bike:admin_bike_add' %}" class="btn btn-success me-2">
                    <i class="bi bi-plus-circle"></i> 添加自行车
                </a>
                <a href="{% url 'bike:admin_dashboard' %}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i> 返回仪表盘
                </a>
            </div>
        </div>

        <!-- 搜索和筛选表单 -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-3">
                        <label for="search" class="form-label">搜索</label>
                        <input type="text" class="form-control" id="search" name="search" 
                               value="{{ search }}" placeholder="搜索编号、姓名、学号、型号...">
                    </div>
                    <div class="col-md-2">
                        <label for="category" class="form-label">类别</label>
                        <select class="form-select" id="category" name="category">
                            <option value="">全部类别</option>
                            {% for value, label in categories %}
                            <option value="{{ value }}" {% if category == value %}selected{% endif %}>{{ label }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    {% if is_super_admin %}
                    <div class="col-md-2">
                        <label for="college" class="form-label">学院</label>
                        <select class="form-select" id="college" name="college">
                            <option value="">全部学院</option>
                            {% for value, label in colleges %}
                            <option value="{{ value }}" {% if college_filter == value %}selected{% endif %}>{{ label }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    {% endif %}
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-grid">
                            <a href="{% url 'bike:admin_bike_list' %}" class="btn btn-outline-secondary">
                                <i class="bi bi-arrow-clockwise"></i> 重置
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 批量操作区域 -->
        {% if page_obj %}
        <div class="card mb-3">
            <div class="card-body">
                <form id="batchForm" method="post">
                    {% csrf_token %}
                    <div class="row align-items-center">
                        <div class="col-md-2">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="selectAll">
                                <label class="form-check-label fw-bold" for="selectAll">
                                    全选
                                </label>
                            </div>
                        </div>
                        <div class="col-md-8">
                            <div class="d-flex flex-wrap gap-2 align-items-center">
                                <button type="button" class="btn btn-outline-danger btn-sm" onclick="console.log('批量删除按钮被点击'); batchDelete();">
                                    <i class="bi bi-trash"></i> 批量删除
                                </button>
                                <button type="button" class="btn btn-outline-success btn-sm" onclick="console.log('批量导出按钮被点击'); batchExportQR();">
                                    <i class="bi bi-download"></i> 导出二维码
                                </button>
                                <button type="button" class="btn btn-outline-warning btn-sm" onclick="batchRefreshQR()">
                                    <i class="bi bi-arrow-clockwise"></i> 刷新二维码
                                </button>
                                <a href="{% url 'bike:bike_batch_import' %}" class="btn btn-outline-success btn-sm">
                                    <i class="bi bi-upload"></i> 批量导入
                                </a>
                                <a href="{% url 'bike:bike_import_template' %}" class="btn btn-outline-secondary btn-sm">
                                    <i class="bi bi-download"></i> 下载模板
                                </a>
                                <a href="{% url 'bike:export_bikes_excel' %}?search={{ search }}&category={{ category }}&college_filter={{ college_filter }}" 
                                   class="btn btn-outline-primary btn-sm">
                                    <i class="bi bi-file-earmark-excel"></i> 导出Excel
                                </a>
                                <a href="{% url 'bike:export_bikes_csv' %}?search={{ search }}&category={{ category }}&college_filter={{ college_filter }}" 
                                   class="btn btn-outline-secondary btn-sm">
                                    <i class="bi bi-file-earmark-text"></i> 导出CSV
                                </a>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="d-flex justify-content-end">
                                <small class="text-muted">
                                    已选择 <span id="selectedCount">0</span> 项
                                </small>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        {% endif %}

        <!-- 自行车列表 -->
        <div class="card">
            <div class="card-body">
                {% if page_obj %}
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th width="50">
                                    <input type="checkbox" id="selectAllTable" class="form-check-input">
                                </th>
                                <th>编号</th>
                                <th>所有人</th>
                                <th>学号</th>
                                <th>型号</th>
                                <th>类别</th>
                                <th>班级</th>
                                <th>图片</th>
                                <th>二维码</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for bike in page_obj %}
                            <tr>
                                <td>
                                    <input type="checkbox" class="form-check-input bike-checkbox" name="bike_ids" value="{{ bike.id }}">
                                </td>
                                <td>
                                    <span class="fw-bold text-primary">{{ bike.bike_number }}</span>
                                </td>
                                <td>{{ bike.owner_name }}</td>
                                <td>{{ bike.owner_student_id|default:"-" }}</td>
                                <td>{{ bike.model }}</td>
                                <td>
                                    <span class="badge bg-info">{{ bike.get_category_display }}</span>
                                </td>
                                <td>{{ bike.class_name|default:"-" }}</td>
                                <td>
                                    {% if bike.image %}
                                    <img src="{{ bike.image.url }}" alt="自行车图片" class="img-thumbnail" style="width: 50px; height: 50px; object-fit: cover;">
                                    {% else %}
                                    <span class="text-muted">无</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if bike.qr_code %}
                                    <img src="{{ bike.qr_code.url }}" alt="二维码" class="img-thumbnail" style="width: 50px; height: 50px;">
                                    {% else %}
                                    <span class="text-muted">无</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <a href="{% url 'bike:bike_detail' bike.id %}" class="btn btn-sm btn-outline-primary" title="查看详情">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <a href="{% url 'bike:admin_bike_edit' bike.id %}" class="btn btn-sm btn-outline-warning" title="编辑">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <a href="{% url 'bike:refresh_qr_code' bike.id %}" class="btn btn-sm btn-outline-info" title="刷新二维码" onclick="return confirm('确定要刷新这辆自行车的二维码吗？')">
                                            <i class="bi bi-arrow-clockwise"></i>
                                        </a>
                                        <a href="{% url 'bike:admin_bike_delete' bike.id %}" class="btn btn-sm btn-outline-danger" title="删除" onclick="return confirm('确定要删除自行车 {{ bike.bike_number }} 吗？\n\n此操作将同时删除：\n- 自行车基本信息\n- 所有相关的违章记录\n- 上传的图片和二维码\n\n此操作不可撤销！')">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                {% if page_obj.has_other_pages %}
                <nav aria-label="分页导航" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <!-- 首页 -->
                        {% if page_obj.has_previous %}
                        <li class="page-item">
                            <a class="page-link" href="?page=1{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}{% if college_filter %}&college_filter={{ college_filter }}{% endif %}">
                                <i class="bi bi-chevron-double-left"></i> 首页
                            </a>
                        </li>
                        {% endif %}

                        <!-- 上一页 -->
                        {% if page_obj.has_previous %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}{% if college_filter %}&college_filter={{ college_filter }}{% endif %}">
                                <i class="bi bi-chevron-left"></i> 上一页
                            </a>
                        </li>
                        {% endif %}

                        <!-- 页码显示 -->
                        {% for num in page_obj.paginator.page_range %}
                            {% if page_obj.number == num %}
                            <li class="page-item active">
                                <span class="page-link">{{ num }}</span>
                            </li>
                            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                            <li class="page-item">
                                <a class="page-link" href="?page={{ num }}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}{% if college_filter %}&college_filter={{ college_filter }}{% endif %}">{{ num }}</a>
                            </li>
                            {% endif %}
                        {% endfor %}

                        <!-- 下一页 -->
                        {% if page_obj.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}{% if college_filter %}&college_filter={{ college_filter }}{% endif %}">
                                下一页 <i class="bi bi-chevron-right"></i>
                            </a>
                        </li>
                        {% endif %}

                        <!-- 末页 -->
                        {% if page_obj.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ page_obj.paginator.num_pages }}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}{% if college_filter %}&college_filter={{ college_filter }}{% endif %}">
                                末页 <i class="bi bi-chevron-double-right"></i>
                            </a>
                        </li>
                        {% endif %}
                    </ul>
                    
                    <!-- 分页信息 -->
                    <div class="text-center text-muted small mt-2">
                        显示第 {{ page_obj.start_index }} - {{ page_obj.end_index }} 条，共 {{ page_obj.paginator.count }} 条记录
                        （第 {{ page_obj.number }} 页，共 {{ page_obj.paginator.num_pages }} 页）
                    </div>
                </nav>
                {% endif %}

                {% else %}
                <div class="text-center py-5">
                    <i class="bi bi-bicycle display-1 text-muted"></i>
                    <h4 class="text-muted mt-3">暂无自行车信息</h4>
                    <p class="text-muted">请添加自行车信息或调整搜索条件</p>
                    <a href="{% url 'bike:admin_bike_add' %}" class="btn btn-primary">
                        <i class="bi bi-plus-circle"></i> 添加自行车
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成，初始化批量操作功能');
    
    const selectAllCheckbox = document.getElementById('selectAll');
    const selectAllTableCheckbox = document.getElementById('selectAllTable');
    const bikeCheckboxes = document.querySelectorAll('.bike-checkbox');
    const selectedCountSpan = document.getElementById('selectedCount');
    
    // 测试函数是否正确定义
    console.log('batchDelete函数:', typeof batchDelete);
    console.log('batchExportQR函数:', typeof batchExportQR);
    console.log('batchRefreshQR函数:', typeof batchRefreshQR);

    // 全选功能
    function updateSelectAll() {
        const checkedBoxes = document.querySelectorAll('.bike-checkbox:checked');
        const totalBoxes = bikeCheckboxes.length;
        
        selectedCountSpan.textContent = checkedBoxes.length;
        
        if (checkedBoxes.length === 0) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = false;
            selectAllTableCheckbox.indeterminate = false;
            selectAllTableCheckbox.checked = false;
        } else if (checkedBoxes.length === totalBoxes) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = true;
            selectAllTableCheckbox.indeterminate = false;
            selectAllTableCheckbox.checked = true;
        } else {
            selectAllCheckbox.indeterminate = true;
            selectAllCheckbox.checked = false;
            selectAllTableCheckbox.indeterminate = true;
            selectAllTableCheckbox.checked = false;
        }
    }

    // 全选按钮事件
    selectAllCheckbox.addEventListener('change', function() {
        bikeCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateSelectAll();
    });

    selectAllTableCheckbox.addEventListener('change', function() {
        bikeCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateSelectAll();
    });

    // 单个复选框事件
    bikeCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectAll);
    });

    // 初始化
    updateSelectAll();
});

// 批量删除
function batchDelete() {
    console.log('开始批量删除操作');
    const checkedBoxes = document.querySelectorAll('.bike-checkbox:checked');
    console.log('选中的复选框数量:', checkedBoxes.length);
    
    if (checkedBoxes.length === 0) {
        alert('请选择要删除的自行车！');
        return;
    }
    
    // 收集选中的自行车ID
    const bikeIds = [];
    checkedBoxes.forEach(checkbox => {
        bikeIds.push(checkbox.value);
        console.log('添加自行车ID:', checkbox.value);
    });
    console.log('选中的自行车ID:', bikeIds);
    
    if (confirm(`确定要删除选中的 ${checkedBoxes.length} 辆自行车吗？此操作不可撤销！`)) {
        const form = document.getElementById('batchForm');
        if (!form) {
            alert('表单未找到，请刷新页面重试！');
            return;
        }
        
        console.log('表单找到，准备提交');
        console.log('提交表单到:', '{% url "bike:batch_delete" %}');
        
        // 确保表单有正确的action和method
        form.action = '{% url "bike:batch_delete" %}';
        form.method = 'POST';
        
        // 清除现有的隐藏输入
        const existingInputs = form.querySelectorAll('input[name="bike_ids"]');
        existingInputs.forEach(input => input.remove());
        
        // 添加选中的自行车ID到表单
        bikeIds.forEach(bikeId => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'bike_ids';
            input.value = bikeId;
            form.appendChild(input);
            console.log('添加隐藏输入:', bikeId);
        });
        
        // 添加调试信息
        console.log('表单action:', form.action);
        console.log('表单method:', form.method);
        console.log('表单数据:', new FormData(form));
        
        form.submit();
        console.log('表单已提交');
    }
}

// 批量导出二维码
function batchExportQR() {
    console.log('开始批量导出二维码操作');
    const checkedBoxes = document.querySelectorAll('.bike-checkbox:checked');
    console.log('选中的复选框数量:', checkedBoxes.length);
    
    if (checkedBoxes.length === 0) {
        alert('请选择要导出二维码的自行车！');
        return;
    }
    
    // 收集选中的自行车ID
    const bikeIds = [];
    checkedBoxes.forEach(checkbox => {
        bikeIds.push(checkbox.value);
        console.log('添加自行车ID:', checkbox.value);
    });
    console.log('选中的自行车ID:', bikeIds);
    
    if (confirm(`确定要导出选中的 ${checkedBoxes.length} 辆自行车的二维码吗？`)) {
        // 使用现有的表单
        const form = document.getElementById('batchForm');
        if (form) {
            console.log('表单找到，准备提交');
            console.log('提交表单到:', '{% url "bike:batch_export_qr" %}');
            
            // 确保表单有正确的action和method
            form.action = '{% url "bike:batch_export_qr" %}';
            form.method = 'POST';
            form.target = '_blank'; // 在新窗口中打开，确保下载
            
            // 清除现有的隐藏输入
            const existingInputs = form.querySelectorAll('input[name="bike_ids"]');
            existingInputs.forEach(input => input.remove());
            
            // 添加选中的自行车ID到表单
            bikeIds.forEach(bikeId => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'bike_ids';
                input.value = bikeId;
                form.appendChild(input);
                console.log('添加隐藏输入:', bikeId);
            });
            
            // 添加调试信息
            console.log('表单action:', form.action);
            console.log('表单method:', form.method);
            console.log('表单target:', form.target);
            console.log('表单数据:', new FormData(form));
            
            form.submit();
            console.log('表单已提交');
        } else {
            alert('表单未找到，请刷新页面重试！');
        }
    }
}

// 批量刷新二维码
function batchRefreshQR() {
    const checkedBoxes = document.querySelectorAll('.bike-checkbox:checked');
    if (checkedBoxes.length === 0) {
        alert('请选择要刷新二维码的自行车！');
        return;
    }
    
    // 收集选中的自行车ID
    const bikeIds = [];
    checkedBoxes.forEach(checkbox => {
        bikeIds.push(checkbox.value);
    });
    
    if (confirm(`确定要刷新选中的 ${checkedBoxes.length} 辆自行车的二维码吗？这将重新生成二维码文件。`)) {
        const form = document.getElementById('batchForm');
        if (form) {
            form.action = '{% url "bike:batch_refresh_qr" %}';
            form.method = 'POST';
            form.target = '_self';
            
            // 清除现有的隐藏输入
            const existingInputs = form.querySelectorAll('input[name="bike_ids"]');
            existingInputs.forEach(input => input.remove());
            
            // 添加选中的自行车ID到表单
            bikeIds.forEach(bikeId => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'bike_ids';
                input.value = bikeId;
                form.appendChild(input);
            });
            
            form.submit();
        } else {
            alert('表单未找到，请刷新页面重试！');
        }
    }
}
</script>

{% endblock %}
